package com.example.demo.aop;

import com.example.demo.annotate.Permission;
import com.example.demo.common.constant.ResultCode;
import com.example.demo.exception.VisitException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
@Order(101)
@Slf4j
public class PermissionAop {

    @Pointcut("@annotation(com.example.demo.annotate.Permission)")
    public void PermissionAop() {

    }

    @Around("PermissionAop()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String identity = request.getHeader("user_identity");

        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Permission permission = method.getAnnotation(Permission.class);

        List<String> identityList = Arrays.asList(permission.identity());
        if (identity == null || !identityList.contains(identity)) {
            log.info(ResultCode.USER_IDENTITY_ERROR.getMessage());
            throw new VisitException(ResultCode.USER_IDENTITY_ERROR);
        }

        return joinPoint.proceed();
    }
}
